import React, { useContext, useState } from "react";

// 声明类型
type ContextProps = { count: number, setCount: React.Dispatch<React.SetStateAction<number>> }
// 1.全局创建
const MyContext = React.createContext<ContextProps>({} as ContextProps);

export const ContextFun: React.FC = () => {
    const [count, setCount] = useState(0);

    // 2.父组件使用
    return <MyContext.Provider value={{ count, setCount }}>
        <h1>当前数据：{count}</h1>
        <Son1></Son1>
        <Son2></Son2>
    </MyContext.Provider>

}


export const Son1: React.FC = () => {
    const publicData = useContext(MyContext);
    const AddFun = ()=>{
        publicData.setCount(publicData.count + 1)
    }
    return (
        <>
            <h1>第一个子元素</h1>
            <button onClick={AddFun}>+1</button>
        </>
    )
}

export const Son2: React.FC = () => {
    const publicData = useContext(MyContext);
    const Decrement = ()=>{
        publicData.setCount(publicData.count - 1);
    }
    const getDate = ()=>{
        const DateFun = new Date();
        console.log(DateFun.toLocaleString());
    }
    return (
        <>
            <h1>第二个子元素：获取父元素值{publicData.count}</h1>
            <button onClick={Decrement}>_1</button>
            <button onClick={getDate}>获取</button>
            <LevelC></LevelC>
        </>
    )
}

export const LevelC:React.FC = ()=>{
    const publicData = useContext(MyContext);
    const Rest = ()=>{
        publicData.setCount(0)
    }
    return(
        <div>
            <h1>孙子组件中 使用父组件的值：{publicData.count}</h1>
            <button onClick={Rest}>重置</button>
        </div>
    )
}